<template>
  <div class="invitation-list-container">
    <!-- 返回按钮 -->
    <div class="back-section">
      <button class="back-button" @click="goBack" title="返回商品列表">
        <i class="fas fa-arrow-left"></i>
      </button>
    </div>
    
    <h1 class="page-title">帖子列表</h1>

    <!-- 搜索栏 -->
    <div class="search-section">
      <div class="search-controls">
        <!-- 排序选择 -->
        <div class="sort-section">
          <label for="sortSelect" class="sort-label">排序方式：</label>
          <el-select 
            id="sortSelect"
            v-model="sortType" 
            placeholder="请选择排序方式" 
            style="width: 150px"
            @change="handleSortChange"
          >
            <el-option label="按点赞量排序" value="按点赞量排序"></el-option>
            <el-option label="按阅读量排序" value="按阅读量排序"></el-option>
            <el-option label="按创建时间排序" value="按创建时间排序"></el-option>
          </el-select>
        </div>
        
        <!-- 搜索区域 -->
        <div class="search-area">
          <el-select v-model="searchType" placeholder="搜索类型" style="width: 120px">
            <el-option label="全部" value="all"></el-option>
            <el-option label="标题" value="title"></el-option>
            <el-option label="分类" value="category"></el-option>
            <el-option label="作者" value="username"></el-option>
          </el-select>
          
          <el-input
            v-model="searchKeyword"
            placeholder="请输入搜索关键词"
            style="width: 300px; margin-left: 10px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch" :loading="searching">
                <i class="fas fa-search"></i>
              </el-button>
            </template>
          </el-input>
          
          <el-button @click="resetSearch" style="margin-left: 10px">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-loading :loading="loading" text="加载中..."></el-loading>
    </div>

    <!-- 帖子列表 -->
    <div v-else-if="invitationList.length > 0" class="invitation-grid">
      <div 
        v-for="invitation in invitationList" 
        :key="invitation.id"
        class="invitation-card"
        @click="goToDetail(invitation.id)"
      >
        <!-- 封面图片 -->
        <div class="card-image">
          <img 
            v-if="invitation.coverImage" 
            :src="invitation.coverImage" 
            :alt="invitation.postTitle"
            @error="handleImageError"
          >
          <div v-else class="no-image">
            <i class="fas fa-image"></i>
            <span>暂无图片</span>
          </div>
        </div>

        <!-- 卡片内容 -->
        <div class="card-content">
          <h3 class="card-title">{{ invitation.postTitle }}</h3>
          <p class="card-excerpt">{{ getExcerpt(invitation.postContent) }}</p>
          
          <div class="card-meta">
            <span class="category">{{ invitation.categoryName }}</span>
            <span class="author">{{ invitation.userName }}</span>
          </div>
          
          <div class="card-stats">
            <span class="stat-item">
              <i class="fas fa-eye"></i>
              {{ invitation.viewCount || 0 }}
            </span>
            <span class="stat-item">
              <i class="fas fa-heart"></i>
              {{ invitation.likeCount || 0 }}
            </span>
            <span class="stat-item">
              <i class="fas fa-comment"></i>
              {{ invitation.commentCount || 0 }}
            </span>
          </div>
          
          <div class="card-time">
            {{ formatTime(invitation.createTime) }}
          </div>
        </div>

        <!-- 操作按钮（仅作者可见） -->
        <div v-if="isAuthor(invitation.userName)" class="card-actions">
          <el-button size="small" @click.stop="editInvitation(invitation)">
            <i class="fas fa-edit"></i>
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click.stop="deleteInvitation(invitation.id)"
          >
            <i class="fas fa-trash"></i>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <i class="fas fa-inbox"></i>
      <h3>暂无帖子</h3>
      <p>{{ searchKeyword ? '没有找到相关帖子，请尝试其他关键词' : '还没有任何帖子，快来发布第一个吧！' }}</p>
      <el-button type="primary" @click="goToCreate">发布帖子</el-button>
    </div>

    <!-- 新建按钮 -->
    <el-button 
      type="primary" 
      class="fab-button"
      @click="goToCreate"
      circle
    >
      <i class="fas fa-plus"></i>
    </el-button>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { invitationAPI } from '../services/api';

const router = useRouter();

// 响应式数据
const loading = ref(false);
const searching = ref(false);
const invitationList = ref([]);
const searchType = ref('all');
const searchKeyword = ref('');
const sortType = ref('按点赞量排序'); // 新增排序类型

// 当前用户信息
const currentUser = computed(() => {
  const userInfo = localStorage.getItem('userInfo');
  return userInfo ? JSON.parse(userInfo) : null;
});

// 判断是否为作者
const isAuthor = (userName) => {
  return currentUser.value && currentUser.value.name === userName;
};

// 返回到商品列表
const goBack = () => {
  router.push('/products');
};

// 获取帖子列表
const fetchInvitationList = async (sortBy = null) => {
  try {
    loading.value = true;
    const sortParam = sortBy || sortType.value;
    console.log('获取帖子列表，排序方式:', sortParam);
    const response = await invitationAPI.queryInvitationList(sortParam);
    invitationList.value = response.data || [];
    console.log('获取到的帖子数据:', invitationList.value);
  } catch (error) {
    console.error('获取帖子列表失败:', error);
    ElMessage.error(error.message || '获取帖子列表失败');
    invitationList.value = [];
  } finally {
    loading.value = false;
  }
};

// 处理排序变化
const handleSortChange = (newSortType) => {
  console.log('排序方式变化:', newSortType);
  sortType.value = newSortType;
  // 如果正在搜索，则保持搜索状态，否则重新获取列表
  if (searchKeyword.value.trim()) {
    handleSearch();
  } else {
    fetchInvitationList(newSortType);
  }
};

// 搜索功能
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    await fetchInvitationList();
    return;
  }

  try {
    searching.value = true;
    let response;
    
    console.log('执行搜索，类型:', searchType.value, '关键词:', searchKeyword.value, '排序:', sortType.value);
    
    switch (searchType.value) {
      case 'title':
        response = await invitationAPI.queryInvitationListByTitleWord(searchKeyword.value);
        break;
      case 'category':
        response = await invitationAPI.queryInvitationListByCategoryName(searchKeyword.value);
        break;
      case 'username':
        response = await invitationAPI.queryInvitationListByUsername(searchKeyword.value);
        break;
      default:
        // 全部搜索：先获取排序后的列表，再进行前端过滤
        response = await invitationAPI.queryInvitationList(sortType.value);
        if (response.data) {
          response.data = response.data.filter(item => 
            item.postTitle.includes(searchKeyword.value) ||
            item.postContent.includes(searchKeyword.value) ||
            item.categoryName.includes(searchKeyword.value) ||
            item.userName.includes(searchKeyword.value)
          );
        }
    }
    
    invitationList.value = response.data || [];
    
    if (invitationList.value.length === 0) {
      ElMessage.info('没有找到相关帖子');
    } else {
      ElMessage.success(`找到 ${invitationList.value.length} 个相关帖子`);
    }
  } catch (error) {
    console.error('搜索失败:', error);
    ElMessage.error(error.message || '搜索失败');
    invitationList.value = [];
  } finally {
    searching.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  searchType.value = 'all';
  searchKeyword.value = '';
  sortType.value = '按点赞量排序';
  fetchInvitationList();
};

// 获取摘要
const getExcerpt = (content) => {
  if (!content) return '暂无内容';
  return content.length > 100 ? content.substring(0, 100) + '...' : content;
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false });
};

// 处理图片错误
const handleImageError = (e) => {
  e.target.style.display = 'none';
  e.target.parentNode.innerHTML = '<div class="no-image"><i class="fas fa-image"></i><span>图片加载失败</span></div>';
};

// 跳转到详情页
const goToDetail = (id) => {
  router.push(`/invitation/${id}`);
};

// 跳转到创建页
const goToCreate = () => {
  router.push('/create-invitation');
};

// 编辑帖子
const editInvitation = (invitation) => {
  router.push(`/edit-invitation/${invitation.id}`);
};

// 删除帖子
const deleteInvitation = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个帖子吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    await invitationAPI.deleteInvitation(id);
    ElMessage.success('删除成功');
    await fetchInvitationList(); // 重新获取列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error(error.message || '删除失败');
    }
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchInvitationList();
});
</script>

<style scoped>
.invitation-list-container {
  max-width: none; /* 移除宽度限制 */
  width: 100%; /* 占满屏幕宽度 */
  margin: 0;
  padding: 20px;
  padding-left: 280px; /* 为侧边栏预留空间 */
  padding-right: 40px; /* 右侧也留出空间 */
  min-height: 100vh; /* 占满屏幕高度 */
  box-sizing: border-box;
}

/* 返回按钮样式 */
.back-section {
  margin-bottom: 20px;
}

.back-button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: none;
  background: #42b983;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  box-shadow: 0 2px 8px rgba(66, 185, 131, 0.3);
  transition: all 0.3s ease;
}

.back-button:hover {
  background: #369870;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 185, 131, 0.4);
}

.back-button:active {
  transform: translateY(0);
}

.page-title {
  color: #333;
  border-bottom: 2px solid #42b983;
  padding-bottom: 10px;
  margin-bottom: 30px;
}

/* 搜索栏样式 */
.search-section {
  background: #fff;
  padding: 30px; /* 增大内边距 */
  border-radius: 12px; /* 增大圆角 */
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1); /* 增强阴影 */
  margin-bottom: 40px; /* 增大底部间距 */
}

.search-controls {
  display: flex;
  align-items: flex-start;
  flex-direction: column;
  gap: 15px;
}

.sort-section {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.sort-label {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.search-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  width: 100%;
}

@media (min-width: 768px) {
  .search-controls {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }
  
  .sort-section {
    width: auto;
  }
  
  .search-area {
    width: auto;
  }
}

/* 加载状态 */
.loading-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 帖子网格布局 */
.invitation-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr)); /* 增大卡片最小宽度 */
  gap: 30px; /* 增大卡片间距 */
  margin-bottom: 80px; /* 增大底部间距 */
}

/* 帖子卡片样式 */
.invitation-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

.invitation-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.card-image {
  height: 250px; /* 增大图片区域高度 */
  overflow: hidden;
  position: relative;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.invitation-card:hover .card-image img {
  transform: scale(1.05);
}

.no-image {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #999;
}

.no-image i {
  font-size: 40px;
  margin-bottom: 10px;
}

.card-content {
  padding: 30px; /* 增大内边距 */
}

.card-title {
  font-size: 20px; /* 增大标题字体 */
  font-weight: 600;
  color: #333;
  margin: 0 0 15px 0; /* 增大底部间距 */
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-excerpt {
  color: #666;
  line-height: 1.6; /* 增大行高 */
  margin: 0 0 20px 0; /* 增大底部间距 */
  display: -webkit-box;
  -webkit-line-clamp: 4; /* 显示更多行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  font-size: 15px; /* 稍微增大字体 */
}

.card-meta {
  display: flex;
  gap: 20px; /* 增大间距 */
  margin-bottom: 20px; /* 增大底部间距 */
}

.category {
  background: #42b983;
  color: white;
  padding: 6px 12px; /* 增大内边距 */
  border-radius: 6px; /* 增大圆角 */
  font-size: 13px; /* 稍微增大字体 */
  font-weight: 500;
}

.author {
  color: #666;
  font-size: 15px; /* 增大字体 */
  font-weight: 500;
}

.card-stats {
  display: flex;
  gap: 20px; /* 增大间距 */
  margin-bottom: 15px; /* 增大底部间距 */
  padding: 12px 0; /* 添加上下内边距 */
  border-top: 1px solid #f0f0f0; /* 添加分割线 */
}

.stat-item {
  color: #888;
  font-size: 15px; /* 增大字体 */
  display: flex;
  align-items: center;
  gap: 6px; /* 增大图标与数字间距 */
  font-weight: 500;
}

.stat-item i {
  font-size: 16px; /* 增大图标尺寸 */
}

.card-time {
  color: #999;
  font-size: 13px; /* 稍微增大字体 */
  font-weight: 500;
}

/* 操作按钮 */
.card-actions {
  position: absolute;
  top: 15px; /* 调整位置 */
  right: 15px;
  display: flex;
  gap: 8px; /* 增大间距 */
  opacity: 0;
  transition: opacity 0.3s ease;
}

.invitation-card:hover .card-actions {
  opacity: 1;
}

.card-actions .el-button {
  padding: 8px 12px; /* 增大按钮尺寸 */
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-state i {
  font-size: 64px;
  color: #ddd;
  margin-bottom: 20px;
}

.empty-state h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.empty-state p {
  margin: 0 0 20px 0;
}

/* 悬浮按钮 */
.fab-button {
  position: fixed;
  bottom: 40px; /* 增大底部距离 */
  right: 40px; /* 增大右侧距离 */
  width: 70px; /* 增大按钮尺寸 */
  height: 70px;
  font-size: 28px; /* 增大图标 */
  box-shadow: 0 6px 20px rgba(66, 185, 131, 0.4); /* 增强阴影 */
  z-index: 1000;
}

.fab-button:hover {
  transform: scale(1.1);
  box-shadow: 0 8px 25px rgba(66, 185, 131, 0.5);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .invitation-list-container {
    padding: 10px;
    padding-left: 10px; /* 移动端不需要为侧边栏预留空间 */
  }
  
  .invitation-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .search-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .fab-button {
    bottom: 20px;
    right: 20px;
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .back-button {
    width: 36px;
    height: 36px;
    font-size: 14px;
  }
}
</style>